import ajax from '@/api/ajax'
import axios from 'axios'
import { token } from '../../build/config'
import { getToken } from '@/utils/auth'
const { url } = require("../../build/config");

// console.log(config)

//  url.base_url;
const base_url = `${url.base_url}/api/kbase-file`

function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

export function getFile(id) {
 return ajax({
   url: `${base_url}/${id}`,
   method: "get"
 })
}

export function getFileData(id, version, applyId) {
  return axios.get(`${base_url}/${id}?${version == null ? '': "version=" + version + '&'}${applyId == null ? '': "applyId=" + applyId + '&'}`, {
    responseType: 'arraybuffer',
    headers: {
      Authorization: `${token.token_type} ${getToken()}`
    }
  }).then(res => {
    console.log(res.headers['content-type'].replace(";charset=UTF-8", ""))
    return `data:${res.headers['content-type'].replace(";charset=utf-8", "")};base64,` + btoa(
      new Uint8Array(res.data)
        .reduce((data, byte) => data + String.fromCharCode(byte), '')
    );
  })
}

export function getFileArray(id, version, applyId) {
  return axios.get(`${base_url}/${id}?${version == null ? '': "version=" + version + '&'}${applyId == null ? '': "applyId=" + applyId + '&'}`, {
    responseType: 'arraybuffer',
    headers: {
      Authorization: `${token.token_type} ${getToken()}`
    }
  })
}

export function getFilePlainText(id, version, applyId) {
  return axios.get(`${base_url}/${id}?${version == null ? '': "version=" + version + '&'}${applyId == null ? '': "applyId=" + applyId + '&'}`, {
    headers: {
      Authorization: `${token.token_type} ${getToken()}`
    }
  })
}

export function getFileBlob(id, version, applyId) {
  return axios.get(`${base_url}/${id}?${version == null ? '': "version=" + version + '&'}${applyId == null ? '': "applyId=" + applyId + '&'}`, {
    responseType: 'blob',
    headers: {
      Authorization: `${token.token_type} ${getToken()}`
    }
  })
}

export function upload(data) {
  return axios.post(`${base_url}`, data, {
    headers: {
      "Authorization": `${token.token_type} ${getToken()}`,
      'Content-Type': 'multipart/form-data',
    }
  })
}


export function updateFile(data) {
  return axios.post(`${base_url}/update`, data, {
    headers: {
      "Authorization": `${token.token_type} ${getToken()}`,
      'Content-Type': 'multipart/form-data',
    }
  })
}
